/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.gateway.filter;

import com.arisgo.cloud.core.Constant;
import com.arisgo.cloud.core.token.config.TokenProperties;
import com.arisgo.cloud.core.url.UrlProperties;
import com.arisgo.cloud.core.utils.JwtUtil;
import com.auth0.jwt.RegisteredClaims;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import static com.arisgo.cloud.gateway.utils.ExchangeUtil.sendResponseError;
import static org.springframework.http.HttpStatus.UNAUTHORIZED;

/**
 * 鉴权配置
 *
 * @author Arisgo
 * @since 2024/3/20
 */
@Configuration
@AllArgsConstructor
public class AuthenticationFilter implements GlobalFilter, Ordered {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final RedisTemplate<String, Object> redisTemplate;
    private final TokenProperties tokenProperties;
    private final UrlProperties urlProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (urlProperties.isSkipUrl(request.getURI().getPath())) {
            return chain.filter(exchange);
        }

        String authorization = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        // 鉴权
        if (!StringUtils.hasLength(authorization) || !JwtUtil.verify(authorization, tokenProperties.getTokenSecret())) {
            logger.error("鉴权失败，token异常，请求路径：{}", request.getURI().getPath());
            return sendResponseError(exchange, UNAUTHORIZED);
        }
        // 登陆验证
        String userId = JwtUtil.getClaim(authorization, RegisteredClaims.AUDIENCE, String.class);
        String token = (String) redisTemplate.opsForHash().get(Constant.TOKEN_PREFIX + userId, Constant.ACCESS_TOKEN);
        if (!JwtUtil.getToken(authorization).equals(token)) {
            logger.error("鉴权失败，token失效，请求路径：{}", request.getURI().getPath());
            return sendResponseError(exchange, UNAUTHORIZED);
        }

        return chain.filter(exchange.mutate().request(request).build());
    }

    @Override
    public int getOrder() {
        return -1;
    }

}
